/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lauglog.servlet;

import lauglog.bean.EventBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
import java.util.*;
import javax.servlet.ServletException;
import lauglog.util.MadePlan;
import java.sql.*;
import javax.servlet.annotation.WebServlet;
import lauglog.bean.FriendBean;
import lauglog.bean.UserBean;
import lauglog.util.Friend;


/**
 *
 * @author Kyle
 */
@WebServlet(name = "FriendServlet", urlPatterns = {"/Friends"})
public class FriendsServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
    response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if (action.equalsIgnoreCase("unfriend"))
                unfriend(request,response);
            else if (action.equalsIgnoreCase("event"))
                profileView(request,response);
            else if (action.equalsIgnoreCase("retreive"))
                getFriendPlan(request,response);
            else if (action.equalsIgnoreCase("finish"))
                getFriendEvent(request,response);
            else if (action.equalsIgnoreCase("friendSearch"))
                friendSearch(request,response);
            else if (action.equalsIgnoreCase("friendRequest"))
                friendRequest(request,response);
            else if (action.equalsIgnoreCase("addFriend"))
                addFriend(request,response);
            else if (action.equalsIgnoreCase("viewProfile"))
                viewProfile(request,response);
            else;
        } finally {            
            out.close();
        }
    }

    public void viewProfile(HttpServletRequest request, HttpServletResponse response){
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";

        Connection con = null;
        try{
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            int yourId = ((UserBean)request.getSession().getAttribute("user")).getUserID();
            int friendId = Integer.parseInt(request.getParameter("friendId"));
            
            PreparedStatement friendInfoStatement = con.prepareStatement("SELECT * FROM users u INNER JOIN profile_information pi ON u.UserId = pi.UserId AND u.UserId = ?");
            friendInfoStatement.setInt(1,friendId);
            ResultSet friendRs = friendInfoStatement.executeQuery();
            friendRs.first();
            
            FriendBean friend = new FriendBean();
            friend.setCity(friendRs.getString("City"));
            friend.setState(friendRs.getString("State"));
            friend.setCountry(friendRs.getString("Country"));
            friend.setEducation(friendRs.getString("Education"));
            friend.setFirstName(friendRs.getString("FirstName"));
            friend.setLastName(friendRs.getString("LastName"));
            friend.setHeight(friendRs.getFloat("Height"));
            friend.setWeight(friendRs.getFloat("Weight"));
            friend.setSex(friendRs.getString("Sex"));
            friend.setFriendID(friendRs.getInt("UserId"));
            
            request.getSession().setAttribute("friendInfo", friend);
            response.sendRedirect("profileView.jsp");
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){

            }
        }
    }
    
    /**
     *  removes a friend using an ID from the user's friend list
     * @param friendID the ID of the friend the user wishes to remove from his friend list
     */    
    public void unfriend(HttpServletRequest request, HttpServletResponse response){
        int friendID;
    }

    public void profileView(HttpServletRequest request, HttpServletResponse response){
        int friendID;
    }

    public Vector<MadePlan> getFriendPlan(HttpServletRequest request, HttpServletResponse response){
        int friendID;
        return null;
    }

    public Vector<EventBean> getFriendEvent(HttpServletRequest request, HttpServletResponse response){
        int friendID;
        return null;
    }

    public void friendRequest(HttpServletRequest request, HttpServletResponse response){
        //Initiate variables for database queries
        String url = "jdbc:mysql://localhost/lauglog";
        String dbUserName = "root";
        String dbPassword = "";
        String driver = "com.mysql.jdbc.Driver";

        Connection con = null;
        try{
            //Make the connection
            Class.forName(driver).newInstance();
            con = DriverManager.getConnection(url, dbUserName, dbPassword);
            int yourId = ((UserBean)request.getSession().getAttribute("user")).getUserID();
            
            PreparedStatement friendRequestStatement = con.prepareStatement("INSERT INTO friends (YourId, FriendId, Accepted) VALUES (?,?,?)");
            friendRequestStatement.setInt(1, yourId);
            friendRequestStatement.setInt(2, Integer.parseInt(request.getParameter("friendId")));
            friendRequestStatement.setInt(3, 0);
            friendRequestStatement.executeUpdate();
            
            response.sendRedirect("dashboard.jsp");
            
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                con.close();
            }catch(Exception e){

            }
        }
    }

    public void friendSearch(HttpServletRequest request, HttpServletResponse response ){
           //Initiate variables for database queries
            String url = "jdbc:mysql://localhost/lauglog";
            String dbUserName = "root";
            String dbPassword = "";
            String driver = "com.mysql.jdbc.Driver";

            Connection con = null;
            try{
                
                
                //Make the connection
                Class.forName(driver).newInstance();
                con = DriverManager.getConnection(url, dbUserName, dbPassword);
                
                String friendName = request.getParameter("q");
                int yourId = ((UserBean)request.getSession().getAttribute("user")).getUserID();
                    
                ResultSet friendRs = null;
                
                if(friendName.contains(" ")){
                    int spaceLoc = friendName.indexOf(' ');
                    String firstName = friendName.substring(0,spaceLoc);
                    String lastName = friendName.substring(spaceLoc+1);
                    
                    PreparedStatement friendStatement = con.prepareStatement("SELECT * FROM users u INNER JOIN privacy_information pi ON (u.FirstName LIKE '%"+firstName+"%' OR u.LastName LIKE '%"+lastName+"%' OR '"+firstName+"' LIKE CONCAT(CONCAT('%', u.FirstName),'%') OR '"+lastName+"' LIKE CONCAT(CONCAT('%', u.LastName), '%')) AND u.UserId <> "+yourId+" AND u.UserId = pi.UserId");
                    friendRs = friendStatement.executeQuery();
                }else{
                    PreparedStatement friendStatement = con.prepareStatement("SELECT * FROM users u INNER JOIN privacy_information pi ON (u.FirstName LIKE '%"+friendName+"%' OR u.LastName LIKE '%"+friendName+"%' OR u.UserName LIKE '%"+friendName+"%' OR '"+friendName+"' LIKE CONCAT(CONCAT('%', u.FirstName),'%') OR '"+friendName+"' LIKE CONCAT(CONCAT('%', u.LastName),'%') OR '"+friendName+"' LIKE CONCAT(CONCAT('%', u.UserName),'%')) AND u.UserId <> "+yourId+" AND u.UserId = pi.UserId");
                    friendRs = friendStatement.executeQuery();
                }
                    
                
                Vector<Friend> searchedUsers = new Vector();

                while(friendRs.next()){
                    Friend f = new Friend();
                    f.setFriendId(friendRs.getInt("UserID"));
                    f.setFriendName(friendRs.getString("FirstName")+" "+friendRs.getString("LastName"));
                    f.setFriended(false);
                    f.setPrivacy(friendRs.getInt("Setting"));
                    searchedUsers.add(f);
                }
                //Create test to see if you've friended this person

                String friendTestSql = "SELECT * FROM friends WHERE YourId = ? OR FriendId = ?";

                PreparedStatement friendTest = con.prepareStatement(friendTestSql);
                friendTest.setInt(1, yourId);
                friendTest.setInt(2, yourId);
                ResultSet friendResults = friendTest.executeQuery();

                while(friendResults.next()){
                    if(friendResults.getInt("FriendId") == yourId){
                        for(int i = 0; i < searchedUsers.size(); i++){
                            if(searchedUsers.get(i).getFriendId() == friendResults.getInt("YourId")){
                                searchedUsers.get(i).setFriended(true);
                            }
                        }
                    }else if(friendResults.getInt("YourId") == yourId){
                        for(int i = 0; i < searchedUsers.size(); i++){
                            if(searchedUsers.get(i).getFriendId() == friendResults.getInt("FriendId")){
                                searchedUsers.get(i).setFriended(true);
                            }
                        }
                    }
                }

                request.getSession().setAttribute("searchedFriends", searchedUsers);

                response.sendRedirect("friendsearch.jsp");


            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try{
                    con.close();
                }catch(Exception e){

                }
            }
    }

    public void addFriend(HttpServletRequest request, HttpServletResponse response){
        int friendID;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


